<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="css/mui.css" rel="stylesheet" />
		<style>
			html,
			body {
				height: 100%;
			}
			
			.mui-content {
				height: 100%;
				overflow: auto;
			}
			
			.red-point{
		      position: relative;
		    }
			
		    .red-point::before{
		      content: " ";
		      border: 5px solid #C9394A;/*设置红色*/
		      border-radius:5px;/*设置圆角*/
		      position: absolute;
		      z-index: 3000;
		      right: 0%;
		      margin-right: -10px;
		      margin-top: 0px;
		    }
		</style>
	</head>

	<body>
		<br />
		<ul id="ul_chatSnapshot" class="mui-table-view">
			<!-- <li class="mui-table-view-cell mui-media">
				<div class="mui-media-body">
					<img class="mui-media-object mui-pull-left" src="image/face-default-cat.png">
					<span class="red-point">lcx</span>
					<p class="mui-ellipsis">这里是聊天内容。。。</p>
				</div>
			</li> -->
		</ul>
		<script src="js/mui.js"></script>
		<script src="js/app.js"></script>
		<script type="text/javascript">
			mui.init(); 
			mui.plusReady(function () {
			    var cWebview = plus.webview.currentWebview();
				
				// 添加监听事件,供别处调用
				window.addEventListener("refreshMsgList", function() {
					fetchUnsignedMsg();
					CHAT.init();
				});
				
				// 页面show时,展示好友请求列表,展示消息列表
			    cWebview.addEventListener("show", function() {
					fetchUnsignedMsg();
					loadMsgList();
			    }); 
				
				// 绑定删除聊天记录事件
				mui("#ul_chatSnapshot").on("tap", "#link_delete_chat_history", function(e) {
					var that = this;
					var meInfo = app.getGlobalUserInfoJson();
					var friendId = that.getAttribute("friendId");
					console.log("friendId:" + friendId);
					// 删除本地聊天记录
					app.deleteChatHistory(meInfo.id, friendId);
					// 删除本地聊天快照
					app.deleteChatSnapshot(meInfo.id, friendId);
					// 更新dom节点
					var liParent = that.parentNode.parentNode;
					var ulChatSnapshot = document.getElementById("ul_chatSnapshot");
					ulChatSnapshot.removeChild(liParent);
				});
			});
			
			window.CHAT = {
				webSocket: null,
				init: function () {
					if (window.WebSocket) {
						// 浏览器支持websocket协议
						if (CHAT.webSocket != null
							&& CHAT.webSocket != undefined
							&& CHAT.webSocket.readyState == WebSocket.OPEN) {
							// 已经初始化过，并且连接是开启的，不需要重复初始化
							return false;
						}
						console.log("重新初始化Websocket");
						CHAT.webSocket = new WebSocket(app.wsServerUrl);
						CHAT.webSocket.onopen = CHAT.wsOpen;
						CHAT.webSocket.onclose = CHAT.wsclose;
						CHAT.webSocket.onerror = CHAT.wserror;
						CHAT.webSocket.onmessage = CHAT.wsMessage; 
					} else {
						this.app.showToast("手机设备过旧，请升级手机设备...");
					}
				},
				chat: function (msg) {
					if (CHAT.webSocket != null
						&& CHAT.webSocket != undefined
						&& CHAT.webSocket.readyState == WebSocket.OPEN) {
						// 已经初始化过，并且连接是开启的，发送消息
						CHAT.webSocket.send(msg);
					} else {
						// socket重连,重新发送消息,init和chat方法可以认为是异步的,所以chat方法要设置一下延时
						CHAT.init();
						CHAT.reChat(msg);
					}
					
				},
				reChat: function (msg) {
					console.log("消息重新发送：" + msg);
					setTimeout("CHAT.webSocket.send('" + msg + "')", "1000");
				},
				wsMessage: function (e) {
					var that = this;
					// 转换成JSON对象
					var dataContent = JSON.parse(e.data);
					console.log("接收到消息：" + e.data);
					var action = dataContent.action;
					if (action === app.PULL_FRIENDS) {
						// 重新拉取好友列表
						var wxContactWebview = plus.webview.getWebviewById("wx-contact.html");
						mui.fire(wxContactWebview, "refreshFriendsList");
						return false;
					}
					
					var msgPojo = dataContent.msgPojo;
					var friendId = msgPojo.senderId;
					var msg = msgPojo.msg;
					// 接收到消息显示到聊天窗口
					// 默认消息是未读标志
					var isRead = false;
					var chattingWebview = plus.webview.getWebviewById("chatting-" + friendId);
					if (chattingWebview != null && chattingWebview != undefined) {
						// 聊天页面是打开的时,才进行渲染
						chattingWebview.evalJS("receiveMessage('" + msg + "')");
						isRead = true;
					}
					// 保存聊天记录,flag为2代表是朋友发送的
					var meInfo = app.getGlobalUserInfoJson();
					app.saveChatMessage(meInfo.id, friendId, msg, 2);
					// 保存聊天快照,isRead为false代表未读
					app.saveChatSnapshot(meInfo.id, friendId, msg, isRead);
					// 刷新聊天快照
					loadMsgList();
					
					// 发送签收消息
					batchSignMsg(msgPojo.msgId);
				},
				wsOpen: function () {
					console.log("连接建立成功");
					var userInfo = app.getGlobalUserInfoJson();
					// 构建MsgPojo
					var msgPojo = new app.MsgPojo(userInfo.id, null, null, null);
					// 构建DataContent
					var dataContent = new app.DataContent(app.CONNECT, msgPojo, null);
					// 发送WebSocket
					CHAT.chat(JSON.stringify(dataContent));
					
					// 获取未签收消息
					// fetchUnsignedMsg();
					
					// 定时发送心跳包
					setInterval("CHAT.wsHeartBeat()", 10000);
				},
				wsClose: function () {
					console.log("连接关闭");
				},
				wsError: function () {
					console.log("发生错误");
				},
				wsLogout: function() {
					// 用户退出登陆后调用此方法
					CHAT.webSocket = null;
				},
				wsHeartBeat: function() {
					var dataContent = new app.DataContent(app.KEEPALIVE, null, null);
					CHAT.chat(JSON.stringify(dataContent));
					// 获取未签收消息
					fetchUnsignedMsg();
					// 获取好友信息
					var wxContact = plus.webview.getWebviewById("wx-contact");
					mui.fire(wxContact, "refreshFriendsList");
				}
			};
			
			
			// 加载消息列表
			var loadMsgList = function() {
				var meInfo = app.getGlobalUserInfoJson();
				var snapshotList = app.getChatSnapshot(meInfo.id);
				var snapshotListHtmlStr = "";
				
				for (var i = 0, size = snapshotList.length; i < size; i++) {
					var snapshot = snapshotList[i];
					var friend = app.getFriendFromStorage(snapshot.friendId);
					var friendFaceImg = app.getUserFaceImg(friend.faceImg);
					// 判断是否已读
					var isRead = snapshot.isRead;
					var nicknameStr = friend.nickname;
					if (!isRead) {
						nicknameStr = '<span class="red-point">' + friend.nickname + '</span>';
					}
					var oneHtmlStr = '<li class="mui-table-view-cell mui-media msg-snapshot" toChatFriendId=' + friend.id + ' friendFaceImg=' + friendFaceImg + ' friendNickname=' + friend.nickname + '>' +
										'<div class="mui-slider-right mui-disabled">' +
											'<a id="link_delete_chat_history" friendId="' + friend.id + '" class="mui-btn mui-btn-red">删除</a>' +
										'</div>' +
										'<div class="mui-media-body mui-slider-handle">' +
											'<img class="mui-media-object mui-pull-left" src="' + friendFaceImg + '">' +
											nicknameStr +
											'<p class="mui-ellipsis">' + snapshot.msg + '</p>' +
										'</div></li>';
					snapshotListHtmlStr += oneHtmlStr;
				}
				var ul_chatSnapshot = document.getElementById("ul_chatSnapshot");
				ul_chatSnapshot.innerHTML = snapshotListHtmlStr;
				
				// 绑定点击事件
				mui("#ul_chatSnapshot").on("tap", "li", function() {
					var friendId = this.getAttribute("toChatFriendId");
					var friendNickname = this.getAttribute("friendNickname");
					var friendFaceImg = this.getAttribute("friendFaceImg");
					mui.openWindow({
						url: "chatting.html",
						id: "chatting-" + friendId,
						extras: {
							friendId: friendId,
							friendUsername: friendNickname,
							friendFaceImg: friendFaceImg
						}
					});
					// 消息未读变已读
					app.changeMsgToRead(meInfo.id, friendId);
					// 重新渲染聊天快照
					loadMsgList();
				});
			};
			
			/**
			 * 获取未签收的消息
			 */
			function fetchUnsignedMsg() {
				var userInfo = app.getGlobalUserInfoJson();
				mui.ajax(app.serverUrl + "/msg/getUnsignedMsg?userId=" + userInfo.id, {
					dataType:'json',//服务器返回json格式数据
					type:'get',//HTTP请求类型
					timeout:10000,//超时时间设置为10秒；              
					success:function(data){
						console.log("++++++++" + JSON.stringify(data));
						
						if (data.code == 200) {
							var msgList = data.data;
							
							var msgIds = "";
							for (var i = 0, size = msgList.length; i < size; i++) {
								var unitMsg = msgList[i];
								// 保存聊天记录
								app.saveChatMessage(unitMsg.acceptUserId, unitMsg.sendUserId, unitMsg.msg, 2);
								// 保存聊天快照
								app.saveChatSnapshot(unitMsg.acceptUserId, unitMsg.sendUserId, unitMsg.msg, false);
								msgIds += unitMsg.id + ",";
							}
							// 消息批量签收
							batchSignMsg(msgIds);
							// 重新加载聊天快照列表
							loadMsgList();
						} else {
							app.showToast(data.msg, "error");
						}
					}
				});
			};
			
			/**
			 * 消息批量签收
			 * @param {Object} msgIds	消息id，中间以","分隔
			 */
			function batchSignMsg(msgIds) {
				// 构建DataContent
				var dataContentSign = new app.DataContent(app.SIGN, null, msgIds);
				CHAT.chat(JSON.stringify(dataContentSign));
			};
		</script>
	</body>
	

</html>
